import request from './request';
import { Rule } from 'ant-design-vue/es/form';
import arrayToTree from 'array-to-tree';

interface BaseTransListDataToTreeTable<T> {
  parentId: string;
  id: string;
  children: T[];
}
export function testTel(val: number) {
  return /^1[3,4,5,6,7,8,9][0-9]{9}$/.test(val.toString());
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: any) {
  return /^(https?:|mailto:|tel:)/.test(path);
}

// 判断是否为系统客服IM账号
export function isSystemIm(account: string) {
  return (
    account.indexOf('IMKF') !== -1 ||
    account.indexOf('XSBZJ') !== -1 ||
    account.indexOf('FWZS') !== -1 ||
    account.indexOf('SWZX') !== -1
  );
}

// 首字母大小
export function titleCase(str: string) {
  return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}

// 下划转驼峰
export function camelCase(str: string) {
  return str.replace(/_[a-z]/g, (str1) => str1.substr(-1).toUpperCase());
}

export function isNumberStr(str: string) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str);
}

// -转驼峰
export function toCamelCase(str: string, upperCaseFirst: boolean) {
  str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
    return group1.toUpperCase();
  });

  if (upperCaseFirst && str) {
    str = str.charAt(0).toUpperCase() + str.slice(1);
  }

  return str;
}

//菜单list转tree结构
export function transListDataToTreeData<
  T extends BaseTransListDataToTreeTable<any>
>(list: T[], root: string) {
  let arrData: T[] = [];
  arrData = arrayToTree(list, { parentProperty: 'parentId', customID: 'id' });
  // 1.遍历
  /* list.forEach((item) => {
        // 2.首次传入空字符串  判断list的pid是否为空 如果为空就是一级节点
        if (item.parentId == root) {
            // 找到之后就要去找item下面有没有子节点  以 item.id 作为 父 id, 接着往下找
            const children = transListDataToTreeData(list, item.id)
            if (children.length > 0) {
                // 如果children的长度大于0,说明找到了子节点
                item.children = children
            }
            // 将item项, 追加到arr数组中
            arrData.push(item )
        }
    })*/
  return arrData;
}

export function transListDataToTreeData2<
  T extends BaseTransListDataToTreeTable<any>
>(list: T[], root: string) {
  let arrData: T[] = [];
  // 1.遍历
  list.forEach((item) => {
    // 2.首次传入空字符串  判断list的pid是否为空 如果为空就是一级节点
    if (item.parentId == root) {
      // 找到之后就要去找item下面有没有子节点  以 item.id 作为 父 id, 接着往下找
      const children = transListDataToTreeData2(list, item.id);
      if (children.length > 0) {
        // 如果children的长度大于0,说明找到了子节点
        item.children = children;
      }
      // 将item项, 追加到arr数组中
      arrData.push(item);
    }
  });
  return arrData;
}

//下载
export function downflie(url: any, data: any, fileName: string) {
  let headers = {
    notCheckCode: 'true'
  };
  request({
    url: url,
    method: 'GET',
    responseType: 'blob',
    params: data,
    headers: headers
  }).then((res: any) => {
    if (res.size > 0) {
      const content = res;
      const blob = new Blob([content]);

      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName);
      }
    }
  });
}

//下载
export const blobDownloadFile = (res: any, type: string, fileName: string) => {
  const blob = new Blob([res], {
    type: type
  });
  const a = document.createElement('a');
  const URL = window.URL || window.webkitURL;
  const herf = URL.createObjectURL(blob);
  a.href = herf;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(herf);
};
export const downloadXsl = (data: any, fileName: string, mineType: any) => {
  // 创建 blob
  let blob = new Blob([data], { type: mineType });
  // 创建 href 超链接，点击进行下载
  window.URL = window.URL || window.webkitURL;
  let href = URL.createObjectURL(blob);
  let downA = document.createElement('a');
  downA.href = href;
  downA.download = fileName;
  downA.click();
  window.URL.revokeObjectURL(href);
};

// zip 下载文件流
export const downloadZip = (
  url: any,
  data: any,
  method: any,
  fileName: any
) => {
  request({
    url,
    method,
    responseType: 'blob', // 指定响应类型为 Blob
    data
  })
    .then((response: any) => {
      // 构建下载链接
      const url = window.URL.createObjectURL(new Blob([response]));
      // 创建一个隐形的 <a> 元素进行下载
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName + '.zip'; // 下载时指定的文件名

      // 触发点击事件进行下载
      link.click();

      // 清理创建的对象 URL
      window.URL.revokeObjectURL(url);
    })
    .catch((error) => {
      console.error('下载 ZIP 文件时出错：', error);
    });
};

export const replaceMobile = (tel: string) => {
  if (tel == undefined || tel == null) {
    tel = '';
  }
  let result = tel.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'); // 截取字符串的前三项  + **** + 截取字符串的第七项之后的字符串
  return result;
};
// 千分位转换
export const formatTableProperties = (tableData: any, properties: any) => {
  const formattedData = tableData.map((row: any) => {
    const formattedRow = { ...row };
    properties.forEach((property: any) => {
      if (typeof formattedRow[property] === 'string') {
        formattedRow[property] = parseFloat(formattedRow[property]);
      }
      formattedRow[property] = formattedRow[property]
        .toFixed(2)
        .replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
    });
    return formattedRow;
  });
  return formattedData;
};

export const validatePhone = async (_rule: Rule, value: string) => {
  const regExp = /^(0\d{2,3}-\d{7,8}|(86)?1[3456789]\d{9})$/;
  if (!value) {
    return Promise.reject('请输入手机号');
  } else if (!regExp.test(value)) {
    return Promise.reject(new Error('请输入正确的手机号'));
  } else {
    return Promise.resolve();
  }
};

export const mergeArray = (arr1:any, arr2:any) => {
  var _arr = new Array();
  for (var i = 0; i < arr1.length; i++) {
    _arr.push(arr1[i]);
  }
  for (var i = 0; i < arr2.length; i++) {
    var flag = true;
    for (var j = 0; j < arr1.length; j++) {
      if (arr2[i] == arr1[j]) {
        flag = false;
        break;
      }
    }
    if (flag) {
      _arr.push(arr2[i]);
    }
  }
  return _arr;
};

// 日期格式转换(yy-mm-dd HH:mm:ss)
export function parseTime(value: string | number | Date) {
  let date = new Date(value);
  let y = date.getFullYear();
  let MM = (date.getMonth() + 1) as number;
  MM = MM < 10 ? (('0' + MM) as unknown as number) : MM;
  let d = date.getDate();
  d = d < 10 ? (('0' + d) as unknown as number) : d;
  let h = date.getHours();
  h = h < 10 ? (('0' + h) as unknown as number) : h;
  let m = date.getMinutes();
  m = m < 10 ? (('0' + m) as unknown as number) : m;
  let s = date.getSeconds();
  s = s < 10 ? (('0' + s) as unknown as number) : s;
  return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
}
// 日期格式转换(yyyy-MM-dd)
export function parseDate(value: string | number | Date) {
  let date = new Date(value);
  let y = date.getFullYear();
  let MM = (date.getMonth() + 1) as number;
  MM = MM < 10 ? (('0' + MM) as unknown as number) : MM;
  let d = date.getDate();
  d = d < 10 ? (('0' + d) as unknown as number) : d;
  return y + '-' + MM + '-' + d;
}

//超过40个字数 省略号
export // 用js限制字数，超出部分以省略号...显示
function LimitNumber(txt: any, num: number) {
  let str = txt;
  if (str.length >= num) {
    str = str.substr(0, num) + '..';
  }
  return str;
}
